//
//  RepairDetailVC.m
//  AILock
//
//  Created by 谭亚明 on 2020/7/9.
//  Copyright © 2020 tym. All rights reserved.
//

#import "RepairDetailVC.h"
#import "EquipmentModel.h"
#import "UserModel.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "IQKeyboardManager.h"
#import "UserService.h"
#import "LocationVC.h"
#import "YPVideoPickerViewController.h"
#import "Sizes.h"
#import "UITextView+Placeholder.h"
#import "HXPhotoManager.h"
#import "UIView+ZFFrame.h"
#import "UIimage+Extends.h"
#import "UIButton+Gradient.h"
#import "UITextView+Placeholder.h"
#import "ZHFAddTitleAddressView.h"
#import "EquipmentService.h"
#import "HXPhotoViewController.h"
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
@interface RepairDetailVC ()<HXPhotoViewControllerDelegate,ZHFAddTitleAddressViewDelegate,UIScrollViewDelegate>

@property(nonatomic,strong) EquipmentModel *equipModel;

@property(nonatomic,weak) IBOutlet UITextField *userNameFid;
@property(nonatomic,weak) IBOutlet UITextField *mobileFid;
@property(nonatomic,weak) IBOutlet UITextField *addressLab;
@property(nonatomic,weak) IBOutlet UITextView *detailAddressFid;
@property(nonatomic,weak) IBOutlet UITextView *questionDecTex;
@property(nonatomic,weak) IBOutlet UILabel *texCount;
@property(nonatomic,strong) EquipmentService *services;
@property(nonatomic,weak) IBOutlet UIButton *goBtn;

@property(nonatomic,weak) IBOutlet UIView *topView;
@property(nonatomic,weak) IBOutlet UIView *centerView;
@property(nonatomic,weak) IBOutlet UIView *bottomView;

@property(nonatomic,strong) UIScrollView *scrollView;
@property (strong, nonatomic) HXPhotoManager *manager;//相册manager

@property(nonatomic,copy) NSString *photoStr;
@property(nonatomic,copy) NSString *videoStr;

@property(nonatomic,weak) IBOutlet UIButton *photoBtn;
@property(nonatomic,weak) IBOutlet UIButton *canPhotoBtn;
@property(nonatomic,weak) IBOutlet UIButton *videoBtn;
@property(nonatomic,weak) IBOutlet UIButton *canVideoBtn;

@property(nonatomic,strong) AMapPOI *mapPoi;
@property(nonatomic,strong) AMapLocationReGeocode *mapRegeo;
@end

@implementation RepairDetailVC

-(instancetype)initEquipMent:(EquipmentModel*)model{
    self = [super init];
    if(self){
        self.equipModel = model;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addBackBtnFunc];
    [self addTitle:@"设备报修"];
    
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight - NavigateonHeight - 75 - SafeBottomMargin );
    _scrollView.backgroundColor = viewBGColor;
    _scrollView.delegate = self;
    [self.view addSubview:self.scrollView];
    
    _topView.frame = CGRectMake(15, 15, ScreenWidth - 30, 297);
    [self.scrollView addSubview:_topView];
    
    _centerView.frame = CGRectMake(15, _topView.zf_bottom + 15, ScreenWidth - 30, 134);
    _videoBtn.layer.masksToBounds = YES;
    _videoBtn.layer.cornerRadius = 5;
    _photoBtn.layer.masksToBounds = YES;
    _photoBtn.layer.cornerRadius = 5;
    [self.scrollView addSubview:_centerView];
    
    self.bottomView.frame = CGRectMake(15, _centerView.zf_bottom + 15, ScreenWidth-30, 167);
    [self.scrollView addSubview:self.bottomView];
    
    self.scrollView.contentSize = CGSizeMake(ScreenWidth, self.bottomView.zf_bottom + 15);
    
    self.mobileFid.text = [UserTool getLogInUser].mobile;
    self.detailAddressFid.placeholder = @"街道，楼牌号等";
    
    self.detailAddressFid.maxInputLength = 200;
    self.detailAddressFid.placeholderAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:13],NSForegroundColorAttributeName:[UIColor colorWithRed:196.0f/255.0f green:196.0f/255.0f blue:196.0f/255.0f alpha:1]};
    self.goBtn.layer.masksToBounds = YES;
    self.goBtn.layer.cornerRadius = 5;
    
    self.questionDecTex.placeholder = @"请填写问题描述，以便我们提供更好地服务";
    
    self.questionDecTex.placeholderAttributes = @{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor colorWithRed:180.0f/255.0f green:180.0f/255.0f blue:180.0f/255.0f alpha:1]};
    self.questionDecTex.maxInputLength = 200;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewChange) name:UITextFieldTextDidEndEditingNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewChange) name:UITextViewTextDidChangeNotification object:nil];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if(self.navigationController.navigationBarHidden){
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}

#pragma mark - 懒加载选择视频的manager
- (HXPhotoManager *)manager {
    if (!_manager) {
        _manager = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypeVideo];
        _manager.configuration.albumShowMode = HXPhotoAlbumShowModePopup;
        _manager.configuration.openCamera = YES;
        _manager.configuration.videoMaxNum = 1;
        _manager.configuration.maxNum = 1;
        _manager.configuration.photoCanEdit = NO;
        _manager.configuration.hideOriginalBtn = YES;
        _manager.configuration.videoCanEdit = NO;
        _manager.configuration.replacePhotoEditViewController = NO;
        _manager.configuration.replaceVideoEditViewController = NO;
        _manager.configuration.showBottomPhotoDetail = NO;
        _manager.configuration.themeColor = [UIColor blackColor];
        _manager.configuration.navBarBackgroudColor = [UIColor blackColor];
        _manager.configuration.navigationTitleColor = [UIColor whiteColor];
        _manager.configuration.selectVideoLimitSize = YES;
        _manager.configuration.limitVideoSize = 1024*1024*100;
        _manager.configuration.photoStyle = HXPhotoStyleDark;
        _manager.configuration.cellDarkSelectBgColor = rgba(76, 132, 255);
        _manager.configuration.languageType = HXPhotoLanguageTypeSc;
        _manager.configuration.reverseDate = YES;
        _manager.configuration.videoMaximumSelectDuration = 60;
    }
    return _manager;
}

-(IBAction)selelPhonetAction:(id)sender{
    self.manager.type  = HXPhotoManagerSelectedTypePhoto;
 
    YPVideoPickerViewController *vc = [[YPVideoPickerViewController alloc] init];
    vc.manager = self.manager;
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}

-(IBAction)seleVideoAction:(id)sender{
    self.manager.type  = HXPhotoManagerSelectedTypeVideo;
    YPVideoPickerViewController *vc = [[YPVideoPickerViewController alloc] init];
    vc.manager = self.manager;
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
}

-(EquipmentService*)services{
    if (_services == nil) {
        _services = [[EquipmentService alloc] init];
    }
    return _services;
}


- (void)textViewChange{
    
    if (self.detailAddressFid.text.length >0) {
        self.detailAddressFid.placeholder = @"";
    }else{
        self.detailAddressFid.placeholder = @"街道,楼牌号等";
    }
    
    self.texCount.text = [NSString stringWithFormat:@"%lu/200",(unsigned long)self.questionDecTex.text.length];
    if (self.questionDecTex.text.length >0) {
        self.questionDecTex.placeholder = @"";
    }else{
        self.questionDecTex.placeholder = @"请填写问题描述，以便我们提供更好地服务";
    }
    
    if (self.userNameFid.text.length > 0 &&
        self.mobileFid.text.length > 0 &&
        self.questionDecTex.text.length > 0) {
        [self.goBtn gradientButtonWithSize:CGSizeMake(300, 44) colorArray:@[(id)rgba(139, 175, 255),(id)rgba(76, 132, 255)] percentageArray:@[@(0.5),@(1)] gradientType:GradientFromLeftTopToRightBottom];
    }else{
        [self.goBtn setBackgroundImage:[UIImage imageWithColor:rgba(230, 230, 230) withSize:self.goBtn.bounds.size] forState:UIControlStateNormal];
    }
}

//选择地址
-(IBAction)seleAddressAction:(id)sender{
    LocationVC *locationVC = [[LocationVC alloc] init];
    TYMWeak(self);
    locationVC.seleAddressBlock = ^(AMapPOI *poi,AMapLocationReGeocode *regeo) {
        weakself.mapPoi = poi;
        weakself.mapRegeo = regeo;
        
        NSString *location = [NSString stringWithFormat:@"%@%@%@",regeo.province,regeo.city,regeo.district];
         weakself.addressLab.text = location;
         weakself.detailAddressFid.text = [NSString stringWithFormat:@"%@%@",poi.address,poi.name];
    };
    [self.navigationController pushViewController:locationVC animated:YES];
}


//提交报修
-(IBAction)submitRepairAction:(id)sender{
    TYMWeak(self);
    
    if (self.userNameFid.text.length ==0 || self.mapRegeo == nil) {
        [WHToast showMessage:@"请选择地址" duration:2 finishHandler:nil];
        return;
    }
    
    [self.services getCreateequipmentrepairsapplyID:_equipModel.equipmentId mobile:self.mobileFid.text userName:self.userNameFid.text address:self.detailAddressFid.text phots:self.photoStr video:self.videoStr applyDesc:self.questionDecTex.text provinceCode:0 province:self.mapRegeo.province cityCode:0 city:self.mapRegeo.city districtCode:self.mapRegeo.adcode district:self.mapRegeo.district rentLng:[NSString stringWithFormat:@"%f",self.mapPoi.location.longitude] rentLat:[NSString stringWithFormat:@"%f", self.mapPoi.location.latitude] completion:^(LMJBaseResponse * _Nonnull respons) {
        if(respons.message){
            [WHToast showMessage:respons.message duration:2 finishHandler:nil];
        }else{
            [WHToast showMessage:@"申请报修成功" duration:2 finishHandler:^{
                [weakself.navigationController popViewControllerAnimated:YES];
            }];
        }
    }];

}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString *blank = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] componentsJoinedByString:@""];
    
    if(![string isEqualToString:blank]) {
        return NO;
    }
    
    if (textField == self.mobileFid) {
        if (textField.text.length >= 11 && ![string isEqualToString:@""]) {
            return NO;
        }
    }else if(textField == self.userNameFid){
        if (textField.text.length >= 8 && ![string isEqualToString:@""]) {
            return NO;
        }
    }
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
//    if (self.detailAddressFid.isFirstResponder) {
//        [self.detailAddressFid resignFirstResponder];
//    }
    
//    if (self.userNameFid.isFirstResponder) {
//        [self.userNameFid resignFirstResponder];
//    }
//    if (self.mobileFid.isFirstResponder) {
//        [self.mobileFid resignFirstResponder];
//    }
//    if (self.questionDecTex.isFirstResponder) {
//        [self.questionDecTex resignFirstResponder];
//    }
}

#pragma mark - HXPhotoViewController delegate
- (void)photoViewController:(HXPhotoViewController *)photoViewController
             didDoneAllList:(NSArray<HXPhotoModel *> *)allList
                     photos:(NSArray<HXPhotoModel *> *)photoList
                     videos:(NSArray<HXPhotoModel *> *)videoList
                   original:(BOOL)original{
    
    if (videoList.count > 0) {
        HXPhotoModel *vidoModel = videoList.firstObject;
        [self.videoBtn setImage:vidoModel.thumbPhoto forState:UIControlStateNormal];
        
        PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
                   options.version = PHVideoRequestOptionsVersionOriginal;

        [[PHImageManager defaultManager] requestAVAssetForVideo:vidoModel.asset options:options resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {

                       if ([asset isKindOfClass:[AVURLAsset class]]) {
                           NSURL *localVideoUrl = [(AVURLAsset *)asset URL];
                           NSData *videoData= [NSData dataWithContentsOfURL:localVideoUrl];
                           [self personalUploadVideoInterfaceWithImage:videoData];
                       }
                   }];
    }
    
    if (photoList.count) {
        HXPhotoModel *vidoModel = photoList.firstObject;
        [self.photoBtn setImage:vidoModel.thumbPhoto forState:UIControlStateNormal];
        [self personalUploadHeadImgInterfaceWithImage:vidoModel.thumbPhoto];
    }
}

- (void)personalUploadHeadImgInterfaceWithImage:(UIImage *)uploadImage  {
    //网络请求管理器
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    NSString *requestUrlStr = [NSString stringWithFormat:@"%@%@", BaseUrl,  urlImageUpload];
    [sessionManager POST:requestUrlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *imageData = UIImageJPEGRepresentation(uploadImage, 1);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@%@.jpg", [UserTool getLogInUser].token, str];
        [formData appendPartWithFileData:imageData name:@"file"  fileName:fileName mimeType:@"image/jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (![responseObject[@"code"] integerValue]) {
            self.photoStr = responseObject[@"data"];
            self.canPhotoBtn.hidden = NO;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [WHToast showMessage:@"上传图片失败" duration:2 finishHandler:nil];
    }];
}

- (void)personalUploadVideoInterfaceWithImage:(NSData *)videoData  {
    //网络请求管理器
    AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
    sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    NSString *requestUrlStr = [NSString stringWithFormat:@"%@%@", BaseUrl,  urlImageUpload];
    [sessionManager POST:requestUrlStr parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //NSData *imageData = UIImageJPEGRepresentation(uploadImage, 1);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@%@.mp4", [UserTool getLogInUser].token, str];
        [formData appendPartWithFileData:videoData name:@"file"  fileName:fileName mimeType:@"image/jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (![responseObject[@"code"] integerValue]) {
            self.videoStr = responseObject[@"data"];
            self.canVideoBtn.hidden = NO;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

-(IBAction)cancelPhotoAction:(id)sender{
    self.photoStr = @"";
    self.canPhotoBtn.hidden = YES;
    [self.photoBtn setImage:[UIImage imageNamed:@"icon_takephoto"] forState:UIControlStateNormal];
}

-(IBAction)cancelVideoAction:(id)sender{
    self.videoStr = @"";
    self.canVideoBtn.hidden = YES;
    [self.videoBtn setImage:[UIImage imageNamed:@"icon／takevideo"] forState:UIControlStateNormal];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
//    if (self.detailAddressFid.isFirstResponder) {
//        [self.detailAddressFid resignFirstResponder];
//    }
    
//    if (self.userNameFid.isFirstResponder) {
//        [self.userNameFid resignFirstResponder];
//    }
//    if (self.mobileFid.isFirstResponder) {
//        [self.mobileFid resignFirstResponder];
//    }
//    if (self.questionDecTex.isFirstResponder) {
//        [self.questionDecTex resignFirstResponder];
//    }
}

@end
